﻿using System.ComponentModel;
using System.Reflection;
using Newtonsoft.Json;

namespace Wechat_PublicNumber
{
    public static class Extensions
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetDescription(this Enum value)
        {
            var descriptionAttribute = ((TypeInfo)value.GetType()).DeclaredFields.Where(s => s.Name == value.ToString()).FirstOrDefault()
                    .GetCustomAttribute<DescriptionAttribute>();
            if (descriptionAttribute != null)
                return descriptionAttribute.Description;
            else
                return value.ToString();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="TClass"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static TClass Convert<TClass>(this object obj) where TClass : class, new()
        {
            if (obj is null) return null;

            var objstring = JsonConvert.SerializeObject(obj);

            if (string.IsNullOrEmpty(objstring)) return null;

            return JsonConvert.DeserializeObject<TClass>(objstring);
        }
    }
}
